package com.zzcm.channelinfo.tools;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.StatFs;
import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import com.zzcm.channelinfo.control.SilentInstallationControl;

/**
 * 工具类
 * @author 张少志
 * 本功能已经基本稳定
 */
public class Tools {
    
    /**
     * 执行一句或多句普通命令
     * @param commandList
     * @return
     */
    public static String runCommand(ArrayList<String> commandList,boolean stopThread[]) {
        if(stopThread[0]||commandList==null||commandList.size()==0)
        {
            return "";
        }
        String result = "";
        Process localProcess = null;
        OutputStream localOutputStream = null;
        DataOutputStream localDataOutputStream = null;//输入流
        InputStream localErrorStream = null;
        DataInputStream localDataErrorStream = null;//错误输出流
        InputStream localInputStream = null;
        DataInputStream localDataInputStream = null;//输出流
        try
        {
            if(!stopThread[0])
            {
                  String  command = SilentInstallationControl.RunCommandParameter.COMMON_USER_COMMAND;
                  String tempCommand;
                  int begin=0;
                  if(commandList.size()==1)
                  {
                      tempCommand = commandList.get(0);
                      if(tempCommand!=null&&!tempCommand.trim().equals(""))
                      {
                          command = tempCommand;
                          begin = 1;
                      }
                  }
                  localProcess = Runtime.getRuntime().exec(command);
                  localOutputStream = localProcess.getOutputStream();
                  localDataOutputStream = new DataOutputStream(localOutputStream);
                  localErrorStream = localProcess.getErrorStream();
                  localDataErrorStream = new DataInputStream(localErrorStream);
                  localInputStream = localProcess.getInputStream();
                  localDataInputStream = new DataInputStream(localInputStream);
                  //向输入流写入所有命令
                  for(int i=begin;!stopThread[0]&&i<commandList.size();i++)
                  {
                      command = commandList.get(i);
                      if(command!=null&&!command.trim().equals(""))
                      {
                          if(!stopThread[0])
                          {
                              localDataOutputStream.writeBytes(command+"\n");
                              localDataOutputStream.flush();
                          }
                          else
                          {
                              break;
                          }
                      }
                  }
                  //接收错误输出流
                  if(!stopThread[0])
                  {
                      command = localDataErrorStream.readLine();
                  }
                  if(!stopThread[0]&&command!=null&&!command.trim().equals(""))
                  {
                      result+= command;
                  }
                  //接收输出流
                  if(!stopThread[0])
                  {
                      command = localDataInputStream.readLine();
                  }
                  if(!stopThread[0]&&command!=null&&!command.trim().equals(""))
                  {
                      result+= command;
                  }
                  if(!stopThread[0])
                  {
                      localDataOutputStream.writeBytes("exit\n");
                      localDataOutputStream.flush();
                      localProcess.waitFor();
                      localDataInputStream.close();
                      localInputStream.close();
                      localDataErrorStream.close();
                      localErrorStream.close();
                      localDataOutputStream.close();
                      localOutputStream.close();
                  }
            }
            return result;
        }
        catch (IOException e)
        {
            result="IOException:"+e.getMessage()+" result="+result;
        }
        catch (SecurityException e)
        {
            result="SecurityException:"+e.getMessage()+" result="+result;
        }
        catch (InterruptedException e)
        {
            result="InterruptedException:Process is timeout!"+e.getMessage()+" result="+result;
        }
        catch (Exception e)
        {
            result="Exception:"+e.getMessage()+" result="+result;
        }
        finally {
            localInputStream = null;
            localDataInputStream = null;
            localErrorStream = null;
            localDataErrorStream = null;
            localOutputStream = null;
            localDataOutputStream = null;
            if (localProcess!= null) {
                localProcess.destroy();
                localProcess = null;
            }
        }
        return result;
    }
    
    /**
     * 使用root用户执行一句或多句命令
     * @param rootCommandList
     * @return
     */
    public static String runRootCommand(ArrayList<String> rootCommandList,boolean stopThread[]) {
        if(stopThread[0]||rootCommandList==null||rootCommandList.size()==0)
        {
            return "";
        }
        String result="";
        Process localProcess = null;
        OutputStream localOutputStream = null;
        DataOutputStream localDataOutputStream = null;
        InputStream localErrorStream = null;
        DataInputStream localDataErrorStream = null;//错误输出流
        InputStream localInputStream = null;
        DataInputStream localDataInputStream = null;
        try
        {
            if(!stopThread[0])
            {
                String rootCommand = SilentInstallationControl.RunCommandParameter.SUPER_USER_COMMAND;
                localProcess = Runtime.getRuntime().exec(rootCommand);//经过Root处理的android系统即有su命令
                localOutputStream = localProcess.getOutputStream();
                localDataOutputStream = new DataOutputStream(localOutputStream);
                localErrorStream = localProcess.getErrorStream();
                localDataErrorStream = new DataInputStream(localErrorStream);
                localInputStream = localProcess.getInputStream();
                localDataInputStream = new DataInputStream(localInputStream);
                //向输入流写入所有命令
                for(int i=0;!stopThread[0]&&i<rootCommandList.size();i++)
                {
                    rootCommand = rootCommandList.get(i);
                    if(rootCommand!=null&&!rootCommand.trim().equals(""))
                    {
                        if(!stopThread[0])
                        {
                            localDataOutputStream.writeBytes(rootCommand+"\n");
                            localDataOutputStream.flush();
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                //接收错误输出流
                if(!stopThread[0])
                {
                    rootCommand = localDataErrorStream.readLine();
                }
                if(!stopThread[0]&&rootCommand!=null&&!rootCommand.trim().equals(""))
                {
                    result+= rootCommand;
                }
                //接收输出流
                if(!stopThread[0])
                {
                    rootCommand = localDataInputStream.readLine();
                }
                if(!stopThread[0]&&rootCommand!=null&&!rootCommand.trim().equals(""))
                {
                    result+= rootCommand;
                }
                if(!stopThread[0])
                {
                    localDataOutputStream.writeBytes("exit\n");
                    localDataOutputStream.flush();
                    localProcess.waitFor();
                    localDataInputStream.close();
                    localInputStream.close();
                    localDataErrorStream.close();
                    localErrorStream.close();
                    localDataOutputStream.close();
                    localOutputStream.close();
                }
            }
            return result;
        }
        catch (IOException e)
        {
            result="IOException:"+e.getMessage()+" result="+result;
        }
        catch (SecurityException e)
        {
            result="SecurityException:"+e.getMessage()+" result="+result;
        }
        catch (InterruptedException e)
        {
            result="InterruptedException:Process is timeout!"+e.getMessage()+" result="+result;
        }
        catch (Exception e)
        {
            result="Exception:"+e.getMessage()+" result="+result;
        }
        finally {
            localInputStream = null;
            localDataInputStream = null;
            localErrorStream = null;
            localDataErrorStream = null;
            localOutputStream = null;
            localDataOutputStream = null;
            if (localProcess!= null) {
                localProcess.destroy();
                localProcess = null;
            }
        }
        return result;
    }
    
    /**
     * 判断该包名的应用是否被安装
     * @param packageName
     * @return
     */
    public static boolean isAppInstalled(Context context,String packageName) {
        if (packageName == null || packageName.trim().equals(""))
        {
            return false;
        }
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,PackageManager.GET_UNINSTALLED_PACKAGES);
            if(info==null)
            {
                return false;
            }
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }
    }
    
    /**
     * 查看SD卡剩余容量
     * @return
     */
    public static long getSDCardAvailableSize() {
        File file = new File(SilentInstallationControl.AppManagerParameter.SDCARD_PATH);
        StatFs statFs = new StatFs(file.getAbsolutePath());
        long availableSpare = (statFs.getBlockSize() * (long)statFs.getAvailableBlocks());
        return availableSpare;
    }
    
    /**
     * 查看手机剩余容量
     * @return
     */
    public static long getPhoneAvailableSize(Context context) {
        File file = new File(SilentInstallationControl.AppManagerParameter.DATA_PATH+"/"+context.getPackageName());
        StatFs statFs = new StatFs(file.getAbsolutePath());
        long availableSpare = (statFs.getBlockSize() * (long)statFs.getAvailableBlocks());
        return availableSpare;
    }
    
    private static boolean showLog=false;//是否打印LOG信息，默认关闭
    /**
     * 开启或关闭LOG信息
     * @param bool
     */
    public static void setShowLog(boolean bool) {
    	showLog=bool;
    }
    
    /**
     * 打印LOG信息
     * @param tag
     * @param msg
     */
    public static void showLog(String tag, String msg) {
        if (showLog) {
            Log.e(tag,msg);
        }
    }
    
    /**
     * 拷贝文件
     * @param fromFilePath
     * @param toFilePath
     * @return
     */
    public static boolean copyFileToFile(String fromFilePath,String toFilePath) {
    	if(fromFilePath==null||toFilePath==null||fromFilePath.trim().equals("")||toFilePath.trim().equals(""))
    	{
    		return false;
    	}
        try {
            FileInputStream fin = new FileInputStream(fromFilePath);
            FileOutputStream fout = new FileOutputStream(toFilePath, false);
            int length = fin.available();
            if(length>0)
            {
	            int k = 1024 * 10;
	            byte data[] = new byte[k];
	            while (length > k) {
	                fin.read(data);
	                fout.write(data);
	                fout.flush();
	                length -= k;
	            }
	            if (length > 0) {
	                fin.read(data, 0, length);
	                fout.write(data, 0, length);
	                fout.flush();
	            }
	            data = null;
	            fout.close();
	            fin.close();
	            fout = null;
	            fin = null;
	            return true;
            }
        } catch (FileNotFoundException e) {
        } catch (SecurityException e) {
        } catch (IOException e) {
        }
        return false;
    }
    
    /**
     * 拷贝文件到手机内存，并授予其它应用的访问权限
     * @param fromFilePath
     * @param toFilePath
     * @return
     */
    public static boolean copyFileToPhone(Context context,String fromFilePath,String fileName,int mode) {
    	if(context==null||fromFilePath==null||fileName==null||fromFilePath.trim().equals("")||fileName.trim().equals(""))
    	{
    		return false;
    	}
        try {
            FileInputStream fin = new FileInputStream(fromFilePath);
            FileOutputStream fout = context.openFileOutput(fileName, mode);
            int length = fin.available();
            if(length>0)
            {
	            int k = 1024 * 10;
	            byte data[] = new byte[k];
	            while (length > k) {
	                fin.read(data);
	                fout.write(data);
	                fout.flush();
	                length -= k;
	            }
	            if (length > 0) {
	                fin.read(data, 0, length);
	                fout.write(data, 0, length);
	                fout.flush();

	            }
	            data = null;
	            fout.close();
	            fin.close();
	            fout = null;
	            fin = null;
	            return true;
            }
        } catch (FileNotFoundException e) {
        } catch (SecurityException e) {
        } catch (IOException e) {
        }
        return false;
    }
    
    /**
     * 判断字符串中是否包含汉字
     * @param str
     * @return
     */
    public static boolean hasChineseCharacter(String str) {
    	if(str!=null&&!str.trim().equals(""))
    	{
    		if(str.getBytes().length > str.length())
    		{
    			return true;
    		}
    	}
    	return false;
    }
    
    /**
     * 判断路径是否为SD卡路径
     * @param path
     * @return
     */
    public static boolean isSdcardPath(String path) {
    	if(path!=null&&!path.trim().equals(""))
    	{
    		path=path.toLowerCase();
    		if(!path.startsWith("/"))
    		{
    			path='/'+path;
    		}
    		if(!path.startsWith("/mnt/"))
    		{
    			path="/mnt"+path;
    		}
    		if(path.startsWith(SilentInstallationControl.AppManagerParameter.SDCARD_PATH+'/'))//"/mnt/sdcard/"
    		{
    			return true;
    		}
    	}
    	return false;
    }
    
    /**
     * 获取转换为ISO-8859-1编码的字符串
     * @param str
     * @return
     */
    public static String getISOString(String str) {
    	if(str!=null&&!str.trim().equals(""))
    	{
    		try {
        		return new String(str.getBytes(),"ISO-8859-1");
    		} catch (UnsupportedEncodingException e) {
    		}
    	}
    	return str;
    }
    
    /**
     * 删除文件
     * @param f
     * @return
     */
    public static boolean deleteFile(File f) {
    	if(f!=null)
    	{
	    	try {
	    		if(f.exists())
	    		{
	    			return f.delete();
	    		}
	    	} catch(SecurityException e) {//文件路径访问安全性异常
	    	}
    	}
    	return false;
    }
    
    /**
     * 判断该包名的应用是否被安装
     * @param packageName
     * @return
     */
    public static PackageInfo getPackageInfo(Context context,String packageName) {
        if (packageName == null || packageName.trim().equals(""))
        {
            return null;
        }
        try {
            return context.getPackageManager().getPackageInfo(packageName,PackageManager.GET_UNINSTALLED_PACKAGES);
        } catch (NameNotFoundException e) {
            return null;
        }
    }
    
    /**
     * 打印字符串链表
     * @param list
     * @return
     */
    public static String showArrayList(ArrayList<String> list) {
        if(list==null)
        {
            return "null";
        }
        String result="[";
        for(int i=0;i<list.size();i++)
        {
            result+=list.get(i);
            if(i!=(list.size()-1))
            {
                result+=",";
            }
        }
        result+="]";
        return result;
    }
    
}
